package cn.edu.zafu.bigdata.mahuilin;

import java.io.*;
import java.util.Scanner;

public class FileAppendOperation {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要追加的文本：");
        String inputText = scanner.nextLine();
        String studentId = "2022010101"; // 假设学号是2022010101，可以根据需要修改
        appendToFile("files/" + studentId + ".txt", inputText);
        System.out.println("文件内容如下：");
        readFile("files/" + studentId + ".txt");
        scanner.close();
    }

    public static void appendToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(fileName), true))) {
            writer.write(content);
            writer.newLine(); // 添加一个新行，以便下一次追加时不会与上一次内容连在一起
        } catch (IOException e) {
            System.err.println("追加到文件时发生错误：" + e.getMessage());
        }
    }

    public static void readFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件时发生错误：" + e.getMessage());
        }
    }
}